{% extends "base.html" %}

{% block title %}多模态检索{% endblock %}

{% block styles %}
<style>
.search-header {
    background: linear-gradient(120deg, #2b5876 0%, #4e4376 100%);
    color: white;
    padding: 2.5rem 0;
    margin-bottom: 2rem;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.search-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 1rem;
}

.search-card {
    border: none;
    border-radius: 15px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    margin-bottom: 2rem;
}

.search-tabs {
    display: flex;
    margin-bottom: 1.5rem;
    background: #f8f9fa;
    border-radius: 12px;
    padding: 0.5rem;
}

.search-tab {
    flex: 1;
    padding: 1rem;
    text-align: center;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    color: #6c757d;
    font-weight: 500;
}

.search-tab.active {
    background: #4e4376;
    color: white;
}

.search-tab:hover:not(.active) {
    background: rgba(78, 67, 118, 0.1);
}

.search-tab i {
    margin-right: 0.5rem;
    font-size: 1.1rem;
}

.search-input {
    background: #f8f9fa;
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 1.5rem;
}

.search-input input {
    border: 2px solid #e9ecef;
    border-radius: 8px;
    padding: 1rem;
    font-size: 1rem;
}

.image-upload {
    border: 2px dashed #e9ecef;
    border-radius: 12px;
    padding: 2rem;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
}

.image-upload:hover {
    border-color: #4e4376;
    background: rgba(78, 67, 118, 0.05);
}

.image-preview {
    max-width: 100%;
    max-height: 300px;
    border-radius: 8px;
    margin-top: 1rem;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.threshold-slider {
    background: #f8f9fa;
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 1.5rem;
}

.search-btn {
    width: 100%;
    padding: 1rem;
    font-size: 1.1rem;
    font-weight: 500;
    border-radius: 10px;
    background: linear-gradient(45deg, #2b5876, #4e4376);
    border: none;
    color: white;
    transition: all 0.3s ease;
}

.search-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(43, 88, 118, 0.3);
}

.result-card {
    border: none;
    border-radius: 12px;
    box-shadow: 0 3px 15px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    margin-bottom: 1.5rem;
    overflow: hidden;
}

.result-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.12);
}

.result-image {
    width: 100%;
    height: 200px;
    object-fit: cover;
}

.result-text {
    padding: 1rem;
    background: white;
}

.similarity-badge {
    position: absolute;
    top: 1rem;
    right: 1rem;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-size: 0.9rem;
}

.no-results {
    text-align: center;
    padding: 4rem 2rem;
    background: #f8f9fa;
    border-radius: 12px;
    color: #6c757d;
}

@media (max-width: 768px) {
    .search-tabs {
        flex-direction: column;
    }
    
    .search-tab {
        margin-bottom: 0.5rem;
    }
}
</style>
{% endblock %}

{% block content %}
<div class="search-header">
    <div class="search-container">
        <h1 class="display-4 mb-2">多模态检索</h1>
        <p class="lead mb-0">支持文搜文、文搜图、图搜图的智能检索系统</p>
    </div>
</div>

<div class="search-container">
    <div class="search-card">
        <div class="card-body">
            <!-- 搜索类型切换 -->
            <div class="search-tabs">
                <div class="search-tab active" onclick="switchType('text2text')">
                    <i class="bi bi-file-text"></i>文搜文
                </div>
                <div class="search-tab" onclick="switchType('text2image')">
                    <i class="bi bi-image-text"></i>文搜图
                </div>
                <div class="search-tab" onclick="switchType('image2image')">
                    <i class="bi bi-images"></i>图搜图
                </div>
            </div>

            <form id="searchForm" onsubmit="performSearch(event)">
                <input type="hidden" name="search_type" id="searchType" value="text2text">
                
                <!-- 文本搜索输入 -->
                <div id="textInput" class="search-input">
                    <input type="text" class="form-control form-control-lg" 
                           name="query" placeholder="请输入搜索关键词...">
                </div>
                
                <!-- 图片搜索上传 -->
                <div id="imageInput" class="search-input" style="display: none;">
                    <div class="image-upload" onclick="document.getElementById('imageFile').click()">
                        <input type="file" id="imageFile" name="image" 
                               accept="image/*" style="display: none;">
                        <i class="bi bi-cloud-upload display-4 mb-3"></i>
                        <p class="mb-0">点击或拖拽图片到此处</p>
                    </div>
                    <img id="imagePreview" class="image-preview" style="display: none;">
                </div>
                
                <!-- 相似度阈值 -->
                <div class="threshold-slider">
                    <label class="form-label d-flex justify-content-between">
                        相似度阈值
                        <span class="badge bg-primary" id="thresholdValue">50%</span>
                    </label>
                    <input type="range" class="form-range" id="similarityThreshold" 
                           name="similarity_threshold" min="0" max="100" value="50" 
                           oninput="updateThreshold(this.value)">
                </div>
                
                <button type="submit" class="search-btn">
                    <i class="bi bi-search me-2"></i>开始搜索
                </button>
            </form>
        </div>
    </div>

    <!-- 搜索结果 -->
    <div id="results" class="row g-4"></div>
    
    <!-- 无结果提示 -->
    <div id="noResults" class="no-results" style="display: none;">
        <i class="bi bi-search display-4 mb-3"></i>
        <h4>未找到匹配结果</h4>
        <p class="text-muted">请尝试调整搜索条件或降低相似度阈值</p>
    </div>
</div>

<!-- 搜索结果模板 -->
<template id="resultTemplate">
    <div class="col-md-4">
        <div class="result-card">
            <div class="position-relative">
                <img class="result-image">
                <span class="similarity-badge"></span>
            </div>
            <div class="result-text">
                <h5 class="card-title text-truncate"></h5>
                <p class="card-text content-preview"></p>
                <div class="d-flex justify-content-between align-items-center">
                    <span class="badge bg-light text-dark category-badge"></span>
                    <small class="text-muted"></small>
                </div>
            </div>
        </div>
    </div>
</template>
{% endblock %}

{% block scripts %}
<script>
function switchType(type) {
    // 更新隐藏字段
    document.getElementById('searchType').value = type;
    
    // 更新标签状态
    document.querySelectorAll('.search-tab').forEach(tab => {
        if (tab.textContent.includes(type === 'text2text' ? '文搜文' : 
            type === 'text2image' ? '文搜图' : '图搜图')) {
            tab.classList.add('active');
        } else {
            tab.classList.remove('active');
        }
    });

    const searchType = document.getElementById('searchType').value;
    const textInput = document.getElementById('textInput');
    const imageInput = document.getElementById('imageInput');
    
    // 根据搜索类型显示/隐藏输入框
    if (searchType === 'image2image' || searchType === 'text2image') {
        textInput.style.display = 'none';
        imageInput.style.display = 'block';
    } else if (searchType === 'text2text') {
        textInput.style.display = 'block';
        imageInput.style.display = 'none';
    }

    // 重置表单和结果
    document.getElementById('searchForm').reset();
    document.getElementById('results').innerHTML = '';
    document.getElementById('noResults').style.display = 'none';
    document.getElementById('imagePreview').style.display = 'none';
}

function updateThreshold(value) {
    document.getElementById('thresholdValue').textContent = value + '%';
}

// 图片预览
document.getElementById('imageFile')?.addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const preview = document.getElementById('imagePreview');
            preview.src = e.target.result;
            preview.style.display = 'block';
        }
        reader.readAsDataURL(file);
    }
});

async function performSearch(event) {
    event.preventDefault();
    
    const searchType = document.getElementById('searchType').value;
    const formData = new FormData(event.target);
    formData.append('search_type', searchType);
    
    // 显示加载状态
    const submitBtn = event.target.querySelector('button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>搜索中...';
    
    try {
        const response = await fetch('/search/api/search', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        if (data.status === 'success') {
            displayResults(data.results);
            // 显示/隐藏无结果提示
            document.getElementById('noResults').style.display = 
                data.results.length === 0 ? 'block' : 'none';
        } else {
            alert(data.message || '搜索失败');
        }
    } catch (error) {
        console.error('搜索错误:', error);
        alert('搜索出错');
    } finally {
        // 恢复按钮状态
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="bi bi-search me-2"></i>开始搜索';
    }
}

function displayResults(results) {
    const container = document.getElementById('results');
    const template = document.getElementById('resultTemplate');
    container.innerHTML = '';
    
    results.forEach(result => {
        const clone = template.content.cloneNode(true);
        const card = clone.querySelector('.result-card');
        
        // 设置标题
        const title = card.querySelector('.card-title');
        title.textContent = result.type === 'text' ? 
            result.text.substring(0, 50) + '...' : 
            result.uri.split('/').pop();
        
        // 设置内容预览
        const preview = card.querySelector('.content-preview');
        const img = card.querySelector('.result-image');
        
        if (result.type === 'text') {
            preview.textContent = result.text.substring(0, 100) + '...';
            preview.style.display = 'block';
            img.style.display = 'none';
        } else {
            preview.style.display = 'none';
            img.src = '/static/' + result.uri;
            img.style.display = 'block';
        }
        
        // 设置相似度和分类
        card.querySelector('.similarity-badge').textContent = 
            `相似度: ${(result.similarity * 100).toFixed(1)}%`;
        card.querySelector('.category-badge').textContent = 
            result.category || '未分类';
        
        container.appendChild(clone);
    });
}

// 初始化页面
switchType('text2text');
</script>
{% endblock %} 